/**
 * Created by lemuelwang on 2017/2/22.
 */
qui(function (require, exports, module) {

    Director.Util = $.extend(true, {}, EpgWeb.Util, {
            formatter: {
                qipuId: function (cellvalue, options, rowObject) {
                    var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(cellvalue);
                    return "<a target='_blank' href='" + plusUrl + "'>" + cellvalue + "</a>";
                },
                programName: function (cellvalue, options, rowObject) {
                    if (rowObject.playStatus == 3) {

                        return "<a class='disabled'>"+cellvalue+"</a>";
                     } else {
                        return "<a href='javascript:;' onclick='Director.Util.jumpToDirector(" + rowObject.programQipuId + ")'>" + cellvalue + "</a>";
                    }
                },
                programStatus: function (cellvalue, options, rowObject) {
                    var current = EpgWeb.Util.formatDateTimeFormat(new Date());
                    var startTime = new Date(rowObject.startPlayTime);
                    startTime.setDate(startTime.getDate() + 2);//回看时间固定为两天
                    var endTimeStr = EpgWeb.Util.formatDateTimeFormat(startTime);
                    if (current < rowObject.startPlayTime) {
                        return "未开始";
                    } else if (current <= rowObject.stopPlayTime) {
                        return "直播中";
                    } else if (current < endTimeStr) {
                        return "回看中";
                    } else {
                        return "已结束";
                    }
                    return cellvalue;
                },
                playStatus: function (cellvalue, options, rowObject) {
                    var ret = ""
                    switch (rowObject.playStatus) {
                        case 0:
                            ret = "导播未开始";
                            break;
                        case 1:
                            ret = "正在导播";
                            break;
                        case 2:
                            ret = "导播停止";
                            break;
                        case 3:
                            ret = "导播结束";
                            break;
                        default :
                            break;
                    }
                    return ret
                },
                operator_list: function (cellvalue, options, rowObject) {
                    var htmlArr = [];
                    if (rowObject.playStatus == 1) {
                        htmlArr.push("<a href='javascript:;' onclick='Director.Util.stopDirector(" + rowObject.id + ")'>停止导播</a>");
                    } else {
                        htmlArr.push("<a class='disabled'>停止导播</a>");
                    }
                    if (rowObject.playStatus == 1) {
                        htmlArr.push("<a href='javascript:;' onclick='Director.Util.releaseDirector(" + rowObject.id + ")'>资源回收</a>");
                    } else {
                        htmlArr.push("<a class='disabled'>资源回收</a>");
                    }

                    htmlArr.push("<a href='javascript:;' onclick='Director.Util.openHistory(" + rowObject.id + ")'>操作日志</a>");
                    htmlArr.push("<a href='javascript:;' onclick='Director.Util.delDirector(" + rowObject.id + ")'>删除</a>");
                    return htmlArr.join(" ")
                },
                log_type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Director.Dao.logType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                }
            },
            stopDirector: function (directorId) {
                Director.Dao.stopDirector({directorId: directorId}, function (data) {
                    Director.Util.reloadListHandler(data)
                });
            },
           releaseDirector: function (directorId) {
               SystemDialog.queryConfirm("回收后不能再次开启导播，确认回收？", function (flag) {
                   if (flag === true) {
                       Director.Dao.releaseDirector({directorId: directorId}, function (data) {
                           if (data != null && data.code == "A00000") {
                               EpgWeb.Plugin.showTips({content: "回收 成功"});
                               $("#list").trigger('reloadGrid');
                           } else {
                               EpgWeb.Plugin.showTips({content: "回收 失败", type: "error"});
                           }
                       })
                   }
               })
            },

            startDirector: function (directorId) {
                Director.Dao.startDirector({ directorId: directorId}, function (data) {
                    Director.Util.reloadListHandler(data)
                });
            },
            jumpToDirector: function (programQipuId) {
                var openUrl = "program_director.html?programQipuId=" + programQipuId
                window.open(openUrl);
            },
            openHistory: function (entityId) {
                Director.Dao.doAuthData({
                    url: '/epg/channel_log.html',
                    doSuccess: function () {
                        Director.Config.AUTH_LOG_DETAIL = true;
                    },
                    doFinal: function () {
                        var tableConfig = $.extend(true, {}, Director.Config.TABLE_LOG);
                        tableConfig.width = Director.Config.AUTH_LOG_DETAIL ? 875 : 425
                        var colModel = tableConfig.colModel;
                        var newColModel = [];
                        var colModelConfig = Director.Config.TABLE_COLMODEL_CONFIG;

                        $.each(colModel, function (i, model) {
                            newColModel.push(colModelConfig[model]);
                        });
                        tableConfig.colModel = newColModel;
                        tableConfig.colModel[4].hidden = !Director.Config.AUTH_LOG_DETAIL;
                        $('#logList').jqGrid(tableConfig);
                        $("#directorLogDiv").dialog({
                            title: "历史记录",
                            autoOpen: false,
                            width: Director.Config.AUTH_LOG_DETAIL ? 900 : 450,
                            height: 600,
                            modal: true,
                            dialogClass: 'alert',
                            open: function () {
                                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                            }
                        });
                        $("#directorLogDiv").dialog("open");
                        $('#logList').jqGrid('setGridParam', {
                            page: 1,
                            datatype: "json",
                            postData: {directorId: entityId}
                        }).trigger('reloadGrid');
                    }
                })
            },
            setTimer: function (start_time, stop_time) {
                var nowTime, endTime, duration;
                var endTime = new Date(start_time); //截止时间
                var stopTime = new Date(stop_time)
                nowTime = new Date();
                if (stopTime.getTime() < nowTime.getTime()) {
                    Director.Model.updateEndMode();
                    Director.Model.stopTimer();
                } else {
                    duration = parseInt(Math.abs(endTime.getTime() - nowTime.getTime()) / 1000);
                    var darArr = [];
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration % 60);
                    duration = ( duration - duration % 60) / 60;
                    darArr.push(duration % 24);
                    duration = ( duration - duration % 24) / 24;
                    if (duration > 0) {
                        darArr.push(duration);
                    }
                    Director.Model.updateTimeModel(darArr);
                    if (!Director.Config.TIME_COLOR_CHANGE) {
                        if (nowTime.getTime() > endTime.getTime()) {
                            Director.Model.updateRunningMode();
                        }
                    }
                }
            },

            calculateDate: function (str) {//month 7days yestoday today
                var from_date = "", to_date = "";
                var d = new Date();
                var defaultEnd = this.formatDateTimeFormat(d);
                this.setZeroTime(d);
                if (str == "today") {
                    from_date = this.formatDateTimeFormat(d);
                    to_date = defaultEnd;
                }
                if (str == "yesterday") {
                    d.setDate(d.getDate() - 1);
                    from_date = this.formatDateTimeFormat(d);
                    this.setDayLastTime(d);
                    to_date = this.formatDateTimeFormat(d);
                }

                if (str == "7days") {
                    d.setDate(d.getDate() - 6);
                    from_date = this.formatDateTimeFormat(d);
                    to_date = defaultEnd
                }
                if (str == "month") {
                    d.setMonth(d.getMonth() - 1);
                    from_date = this.formatDateTimeFormat(d);
                    to_date = defaultEnd
                }
                this.bindDate("startDate", "endDate", { maxDate: to_date, maxDateTime: new Date(to_date.replace(/-/g, "/")), minDate: from_date, minDateTime: new Date(from_date.replace(/-/g, "/"))})
                $("input[name=startDate]").datetimepicker("setDate", new Date(from_date.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate", new Date(to_date.replace(/-/g, "/")));
            },
            submitAddSignal: function () {
                var parnet = $("#dlg_add_signal");
                var signalName = parnet.find("input[name=signal_name]").val();
                if (signalName.length == 0) {
                    EpgWeb.Plugin.showTips({content: "信号名称不能为空", type: "error"});
                    return false;
                }
                var signalType = parnet.find("select[name=signal_type]").val();
                var signalId = "";
                var signalUrl = "";
                var signalPreviewUrl = "";

                if (signalType == "0" || signalType == "1") {
                    signalId = parnet.find("input[name=signal_url_" + signalType + "]").suggest("getValue");
                    if (signalId.length == 0) {
                        EpgWeb.Plugin.showTips({content: "信号源异常", type: "error"});
                        return false;
                    }

                } else if (signalType == "2") {
                    signalUrl = parnet.find("input[name=signal_url_2]").val();
                    signalPreviewUrl = parnet.find("input[name=preview_url]").val();
                    if (!this.checkValidStreamUrl(signalUrl, Director.Config.REG_VALIDATE.HTTP_RTMP_UDP)) {
                        EpgWeb.Plugin.showTips({content: "流地址格式错误,需要( rtmp://或udp://或http://)", type: "error"});
                        return false;
                    }
                    if (signalPreviewUrl != "" && !this.checkValidStreamUrl(signalPreviewUrl, Director.Config.REG_VALIDATE.RTMP_ONLY)) {
                        EpgWeb.Plugin.showTips({content: "流预览地址格式错误,需要( rtmp://）", type: "error"});
                        return false;
                    }
                } else {
                    EpgWeb.Plugin.showTips({content: "信号类型异常", type: "error"});
                    return false
                }
                var baseElement = {
                    signalType: signalType,
                    isDefaultBackup: 0,
                    signalId: signalId,
                    signalName: signalName,
                    signalLegoId: 0
                };
                if (baseElement.signalType == "1") {
                    var labelArr = $("label[name=hint-id]").html().split(/:|;/);
                    baseElement.signalLegoId = Number(labelArr[3]);
                }
                if (baseElement.signalType == "2") {
                    baseElement.signalUrl = signalUrl;
                    baseElement.signalPreviewUrl = signalPreviewUrl;
                }


                var responseData = Director.Dao.getDataByName("entity");
                var entity = responseData.data.result[0];
                baseElement.directorId = entity.id;
                baseElement.programQipuId = entity.programQipuId;
                baseElement.isBackup = 0;

                var tempFunc = function () {
                    Director.Dao.addResource(baseElement, function (data) {
                        if (data != null && data.code == "A00000") {
                            EpgWeb.Plugin.showTips({content: data.msg});
                            var resourceId = data.data;
                            if (signalType == "0" || signalType == "2") {
                                var setMainResourceFlag = parnet.find("input[name=set_main_resource]:checked").val();
                                if (setMainResourceFlag == "1") {
                                    Director.Dao.setDirectorMainResource({pid: entity.programQipuId, mainResourceId: resourceId}, function (data) {
                                        if (data != null && data.code == "A00000") {
                                            var updateEntity = Director.Util.getEntity();
                                            updateEntity.mainResourceId = resourceId;
                                            Director.Util.getResourceList();
                                        } else {
                                            EpgWeb.Plugin.showTips({content: "主信号源设置失败", type: "error"});
                                        }

                                    });
                                } else {
                                    Director.Util.getResourceList();
                                }
                            } else {
                                Director.Util.getResourceList();
                            }

                        } else {
                            EpgWeb.Plugin.showTips({content: data.msg, type: "error"});
                        }
                    })
                }
                if (baseElement.signalType == "0") {
                    var qipuId = Number(baseElement.signalId)
                    var options = {
                        url: Director.urlConfig.queryRtmpUrl,
                        dataType: 'json',
                        data: {qipuId: qipuId},
                        type: "get",
                        success: function (data) {
                            if (data != null && data.code == "A00000") {
                                if (data.data.output_url.length > 0) {
                                    tempFunc();
                                } else {
                                    EpgWeb.Plugin.showTips({content: "没有流不能添加", type: "error"});
                                    console.error("submitAddSignal fail")
                                }
                            }
                        },
                        error: function (data) {
                            console.error("submitAddSignal fail")
                        }
                    }
                    $.ajax(options)
                } else {
                    tempFunc();
                }


                return true;
            },
            submitAddBackUp: function () {
                var parnet = $("#dlg_add_alternatePlay")
                var signalId = parnet.find("input[name=signal_url_1]").suggest("getValue");
                var signalName = parnet.find("input[name=signal_name]").val();
                if (signalName.length == 0) {
                    EpgWeb.Plugin.showTips({content: "信号名称不能为空", type: "error"});
                    return false;
                }
                if (signalId.length == 0) {
                    EpgWeb.Plugin.showTips({content: "信号源异常", type: "error"});
                    return false;
                }
                var baseElement = {
                    signalType: 1,
                    isDefaultBackup: 0,
                    signalId: signalId,
                    signalName: signalName,
                    signalLegoId: 0
                };
                if (baseElement.signalType == "1") {
                    var labelArr = $("label[name=hint-id]").html().split(/:|;/);
                    baseElement.signalLegoId = Number(labelArr[3]);
                }
                if (parnet.find("input[name=default_play]").is(":checked")) {
                    baseElement.isDefaultBackup = 1;
                }

                var responseData = Director.Dao.getDataByName("entity");
                var entity = responseData.data.result[0];
                baseElement.directorId = entity.id;
                baseElement.programQipuId = entity.programQipuId;
                baseElement.isBackup = 1;
                Director.Config.WAITING_MSG = true;
                Director.Dao.addResource(baseElement, function (data) {
                    if (data != null && data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: data.msg});
                        Director.Util.getBackUpList();
                    } else {
                        EpgWeb.Plugin.showTips({content: "添加失败", type: "error"});
                    }
                    Director.Config.WAITING_MSG = false;
                })
                return true;
            },
            makeUpBackUpDiv: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div data-div-id="' + element.id + '" class="small_window_div">');
                htmlArr.push(' <div><img class="gou" src="img/u743.png"  data-id="' + element.id + '" onclick="Director.Util.setDefaultBackUp(this)"><span  onclick="Director.Util.delResource( this ) " data-backup="1" data-id="' + element.id + '">X</span> ' +
                    '<div class="flash" id="flash' + element.id + '"></div>' +
                    '</div>');
                htmlArr.push(' <input data-backup="1" type="text"  value="' + element.signalName + '" data-id="' + element.id + '"  onmouseover="Director.Util.showTipsResourceId(this)"  onblur="Director.Util.updateResourceTitle(this)" onkeyup="Director.Util.updateResourceTitleShortCut(event)" >');
                htmlArr.push(' </div>');
                return htmlArr.join("")
            },
            makeUpResourceType1Div: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div data-div-id="' + element.id + '" class="small_window_div">');
                htmlArr.push(' <div><span onclick="Director.Util.delResource(this)" data-backup="0" data-id="' + element.id + '">X</span> ' +
                    '<div class="flash" id="flash' + element.id + '"></div>' +
                    '</div>');
                htmlArr.push(' <input data-backup="0" type="text"  value="' + element.signalName + '" data-id="' + element.id + '" onmouseover="Director.Util.showTipsResourceId(this)"  onblur="Director.Util.updateResourceTitle(this)" onkeyup="Director.Util.updateResourceTitleShortCut(event)">');
                htmlArr.push(' </div>');
                return htmlArr.join("")
            },
            makeUpResourceDiv: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div data-div-id="' + element.id + '" class="small_window_div">');
                htmlArr.push(' <div><img class="gou" src="img/u743.png" title="点击设置主信号源"  data-id="' + element.id + '" onclick="Director.Util.setDirectorMainResource('+ element.id +')"><span   onclick="Director.Util.delResource(this)" data-backup="0" data-id="' + element.id + '">X</span> ' +
                    '<div class="flash" id="flash' + element.id + '"></div>' +
                    '</div>');
                htmlArr.push(' <input data-backup="0" type="text"  value="' + element.signalName + '" data-id="' + element.id + '" onmouseover="Director.Util.showTipsResourceId(this)"  onblur="Director.Util.updateResourceTitle(this)" onkeyup="Director.Util.updateResourceTitleShortCut(event)">');
                htmlArr.push(' </div>');
                return htmlArr.join("")
            },
            makeUpResourceAddDiv: function (element) {
                var htmlArr = [];
                htmlArr.push(' <div id="resourceAddDiv"  >');
                htmlArr.push(' <div style="background-color: #ffffff;text-align: center"><img id="imgResource"  src="img/addSourceBtn.png" style="margin-top: 30px" onclick="Director.Util.addResource()">');
                htmlArr.push(' <div style="text-align: center;font-size: 14px;color: #b2beca">添加信号源</div> ');
                htmlArr.push('</div>');
                htmlArr.push(' </div>');
                return htmlArr.join("");
            },
            makeUpBackUpAddDiv: function () {
                var htmlArr = [];
                htmlArr.push(' <div id="backUpAddDiv" >');
                htmlArr.push(' <div style="background-color: #ffffff;text-align: center"><img id="imgBackUp" src="img/addSourceBtn.png" style="margin-top: 30px" onclick="Director.Util.addBackUp()">');
                htmlArr.push(' <div style="text-align: center;font-size: 14px;color: #b2beca">添加灾备</div> ');
                htmlArr.push('</div>');
                htmlArr.push(' </div>');
                return htmlArr.join("");
            },

            // type = (1,2,3,4) (图片，字幕，动画，音效)
            makeUpEffectDiv: function (e, type) {
                if (type == 5 && e.name.trim().length == 0) {
                    e.name = "遮标" + e.id;
                }
                var options = encodeURIComponent(JSON.stringify(e));
                var htmlArr = [];
                switch (type) {
                    case 1:
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div class="effect_container"><div class="effect_upper">');
                            htmlArr.push(' <label style="padding-top: 20px;">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </label>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 1)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <img class="content" src="' + e.url + '">');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');
                        } else {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div style="" data-id="' + e.id + '">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 1)">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 1)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 1)">');
                            //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                            //htmlArr.push(' <span onclick="Director.Util.delEffect(this, ' + e.type + ')" data-id="' + e.id + '">X</span>');
                            htmlArr.push(' <img class="content" src="' + e.url + '">');
                            htmlArr.push(' </div>');
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');
                        }
                        break;
                    case 2:
                        if (e.url.length > 32) {
                            e.url = e.url.slice(0,32) + ' ...';
                        }
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_subtitle_div" stype="position: relative;">');
                            htmlArr.push(' <span style="float:left;margin-top:8px;">' + e.url + '</span>');
                            htmlArr.push(' <div class="effect_upper"><div class="effect_hint">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </div>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 2)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div></div>');
                        } else {
                            htmlArr.push(' <div style="position:relative;" data-div-id="' + e.id + '" data=' + options + ' class="effect_subtitle_div" data-id="' + e.id + '">');
                            htmlArr.push(' <span style="position:absolute;margin-top:8px;">' + e.url + '</span>');
                            htmlArr.push(' <div style="position:absolute;right:0px;margin-top:8px;background:#e7f0f7;">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 2)">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 2)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 2)">');
                            htmlArr.push(' </div></div>');
                        }
                        break;
                    case 3:
                        var extraInfo = e.extraInfo != "" ? JSON.parse(e.extraInfo) : {};
                        var imageUrl = extraInfo['foreground'] || "img/default_animation.png";
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div class="effect_container"><div class="effect_upper">');
                            htmlArr.push(' <label style="padding-top: 20px;">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </label>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 3)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <img class="content" src="' + imageUrl + '">');
                            htmlArr.push(' </div>')
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');
                        } else {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div style="">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 3)">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewAnimationEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 3)">');
                            //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 3)">');
                            htmlArr.push(' <img class="content" src="' + imageUrl + '">');
                            htmlArr.push(' </div>');
                            htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            htmlArr.push(' </div>');

                        }
                        break;
                    case 4:
                        var extraInfo = e.extraInfo != "" ? JSON.parse(e.extraInfo) : {};
                        var volumn = extraInfo['volumn'] || '0';
                        htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_audio_div">');
                        htmlArr.push(' <div style="position: relative;">');
                        htmlArr.push(' <input class="volumn-range" data-id="' + e.id + '" type="range" min="0" max="100" value="' + volumn + '" onchange="Director.Util.changeVolumn(this)"/>')
                        htmlArr.push(' <button class="d-btn d-btn-primary play" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 4)">播出</button>');
                        //htmlArr.push(' <img class="change" src="img/u128.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 4)">');
                        //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                        htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 4)">');
                        htmlArr.push(' <img class="content" src="img/default_audio.png">');
                        htmlArr.push(' </div>');
                        //htmlArr.push(' <input class="volumn-range" data-id="' + e.id + '" type="range" min="0" max="100" value="' + volumn + '" onchange="Director.Util.changeVolumn(this)" style="margin-bottom: 10px;width:164px;" />')
                        htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                        htmlArr.push(' </div>');
                        break;
                    case 5:
                        if (e.status == "1") {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div class="effect_container"><div class="effect_upper">');
                            htmlArr.push(' <label style="padding-top: 20px;">');
                            htmlArr.push(' <img class="effect_playing" src="img/u311.png" alt="">正在播出...');
                            htmlArr.push(' </label>');
                            htmlArr.push(' <button class="d-btn effect_stop" onclick="Director.Util.submitStopPlayEffect(this, 5)" data-id="' + e.id + '">停止</button>');
                            htmlArr.push(' </div>')
                            if (e.url.trim().length >0) {
                                htmlArr.push(' <img class="content" src="' + e.url + '">');
                            }else{
                                htmlArr.push(' <img class="content" src="img/director/effect_cover.png">');
                            }
                            htmlArr.push(' </div>')
                            if (e.name.trim().length >0) {
                                htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }else{
                                htmlArr.push(' <input type="text" value="遮标' + e.id + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }
                            htmlArr.push(' </div>');
                        } else {
                            htmlArr.push(' <div data-div-id="' + e.id + '" data=' + options + ' class="effect_element_div">');
                            htmlArr.push(' <div style="" data-id="' + e.id + '">');
                            htmlArr.push(' <img class="change" src="img/director/edit.png" data-id="' + e.id + '" onclick="Director.Util.editEffectShow(this, 5)">');
                            htmlArr.push(' <img class="preview" src="img/effectPreview.png" data-id="' + e.id + '" onclick="Director.Util.previewEffect(this)">');
                            htmlArr.push(' <img class="play" src="img/effectPlay.png" data-id="' + e.id + '" onclick="Director.Util.submitPlayEffect(this, 5)">');
                            htmlArr.push(' <img class="del" src="img/director/delete.png" data-id="' + e.id + '" onclick="Director.Util.delEffect(this, 5)">');
                            //htmlArr.push(' <img class="start" src="img/u618.png" data-id="2" onclick="Director.Util.doResourceSwitch(this)">');
                            //htmlArr.push(' <span onclick="Director.Util.delEffect(this, ' + e.type + ')" data-id="' + e.id + '">X</span>');
                            if (e.url.trim().length >0) {
                                htmlArr.push(' <img class="content" src="' + e.url + '">');
                            }else{
                                htmlArr.push(' <img class="content" src="img/director/effect_cover.png">');
                            }
                            htmlArr.push(' </div>');
                            if (e.name.trim().length >0) {
                                htmlArr.push(' <input type="text" value="' + e.name + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }else{
                                htmlArr.push(' <input type="text" value="遮标' + e.id + '" data-id="' + e.id + '" onblur="Director.Util.updateEffectName(this)" onkeyup="Director.Util.updateEffectNameShortCut(event)">');
                            }

                            htmlArr.push(' </div>');
                        }
                        break;

                }

                return htmlArr.join("");
            },

            makeUpEffectAddDiv: function(type) {
                var htmlArr = [];
                switch (type) {
                    case 1:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label for="effect_img_file_input">');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png">');
                        htmlArr.push('</label>');
                        htmlArr.push('<input id="effect_img_file_input" type="file" style="display:none" class="uploadBtn"/>')
                        htmlArr.push('</div></div>');
                        break;
                    case 3:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label>');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png" onclick="Director.Util.AddAnimationShow();">');
                        htmlArr.push('</label>');
                        htmlArr.push('</div></div>');
                        break;
                    case 4:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label for="effect_audio_file_input">');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png">');
                        htmlArr.push('</label>');
                        htmlArr.push('<input id="effect_audio_file_input" type="file" style="display:none" class="uploadBtn" accept="audio/mpeg"/>')
                        htmlArr.push('</div></div>');
                        break;
                    case 5:
                        htmlArr.push('<div class="effect_element_div"><div style="border:1px solid #aabcc7;text-align: center;">');
                        htmlArr.push('<label>');
                        htmlArr.push('<img style="margin-top: 10px;" src="img/addSourceBtn.png" onclick="Director.Util.AddCoverShow();">');
                        htmlArr.push('</label>');
                        htmlArr.push('</div></div>');
                        break;

                }

                return htmlArr.join("");
            },

            reloadListHandler: function (data) {
                if (data != null) {
                    EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                    if (data.code == "A00000") {
                        $("#list").trigger("reloadGrid")
                    }
                } else {
                    console.log("callbackHandler no return data");
                }
            },
            submitEditDirector: function () {
                var parent = $("#dlg_settings");
                var rtmpUrl = parent.find("input[name=input_out_url]").val();
                var delayTime = parent.find("input[name=delay]").val();
                var streamType = parent.find("select[name=stream_type]").val();
                if (!this.checkValidStreamUrl(rtmpUrl, Director.Config.REG_VALIDATE.HTTP_RTMP_UDP)) {
                    EpgWeb.Plugin.showTips({content: "流格式错误,需要( rtmp://或udp://或http://)", type: "error"});
                    return;
                }
                if (isNaN(delayTime) || parseInt(delayTime) < 0 || parseInt(delayTime) > 30) {
                    EpgWeb.Plugin.showTips({content: "延时时间范围为0~30秒", type: "error"});
                    return;
                }
                var oldEntity = Director.Util.getEntity();

                var newData = $.extend({}, oldEntity);
                newData.outputUrl = rtmpUrl;
                newData.delay = delayTime;
                newData.outputStreamType = streamType;

                Director.Config.DURING_CHANGE_SETTINGS = true;
                Director.Dao.editDirector({entity: JSON.stringify(newData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: "修改导播台成功"});
                        oldEntity.outputUrl = newData.outputUrl;
                        oldEntity.delay = newData.delay;
                        oldEntity.outputStreamType = newData.outputStreamType;
                        Director.Util.initDetailZone(oldEntity);

                        Director.Commentary.checkCommentaryAfterEditDirector();
                        setTimeout("Director.Util.notifyUpdateDirector('" + JSON.stringify(newData) + "')", 3000);
                    } else {
                        EpgWeb.Plugin.showTips({content: "修改导播台失败", type: "error"});
                    }
                    Director.Config.DURING_CHANGE_SETTINGS = false;
                });
            },

            notifyUpdateDirector: function(entity) {
                var data = JSON.parse(entity);

                var request = {};

                request.type = 'post';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'updateprogram' + "?PID=" + data.programQipuId;

                var beginTime = new Date(data.startPlayTime);
                var endTime = new Date(data.stopPlayTime);

                request.params = {
                    ID : parseInt(data.programQipuId),
                    NAME : data.programName,
                    ADDRESS : data.outputUrl,
                    DELAY: parseInt(data.delay),
                    RESOLUTION: data.outputStreamType,
                    BEGINTIME: parseInt(beginTime.getTime()/1000),
                    ENDTIME: parseInt(endTime.getTime()/1000),
                    UPDATEBY: '_system_',
                    MAINSOURCE: data.mainResourceId==0 ? "" : data.mainResourceId
                };

                request.params = JSON.stringify(request.params);

                request.directorId = data.id;
                request.logType = "102";
                request.raw = 1;

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {

                    //self.callback(options);
                })
            },

            submitEditEffect: function (type) {
                var self = this;
                self.type = type;
                var extraInfo = "";
                var location = '';
                var id = '';
                var entity = self.getEntity();
                var url = '';
                var updateData = {};

                switch (type) {
                    case 1:
                        var parent = $("#dlg_edit_image");
                        var params = self.getParams(parent);
                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }

                        extraInfo = params;
                        location = params['location_x'] + ',' + params['location_y'];

                        var size = {};
                        id = params['id'];
                        size.w = params['size_w'];
                        size.h = params['size_h'];
                        extraInfo.size = JSON.stringify(size);

                        // remove unnecessary params
                        delete extraInfo['location_x'];
                        delete extraInfo['location_y'];
                        delete extraInfo['size_w'];
                        delete extraInfo['size_h'];
                        delete extraInfo.id;

                        extraInfo = JSON.stringify(extraInfo);

                        updateData = {
                            id: id,
                            location: location,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };

                        var parent = $('#tabPanel_3');
                        var curDiv = parent.find("div[data-div-id=" + id + "]");
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        options.location = location
                        options.extraInfo = extraInfo

                        self.notifyFlashEditEffect(JSON.stringify(options));

                        //console.log(params);
                        break;
                    case 2:
                        var parent = $("#dlg_edit_subtitle");
                        var params = self.getParams(parent);

                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }

                        extraInfo = params;
                        location = params['location_x'] + ',' + params['location_y'];

                        id = params['id'];
                        url = params['content'];

                        delete extraInfo['location_x'];
                        delete extraInfo['location_y'];
                        delete extraInfo['id'];
                        delete extraInfo['content'];

                        extraInfo = JSON.stringify(extraInfo);

                        updateData = {
                            id: id,
                            location: location,
                            url: url,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };


                        if (id != '') {
                            var parent = $('#tabPanel_3');
                            var curDiv = parent.find("div[data-div-id=" + id + "]");
                            var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                            options.location = location;
                            options.extraInfo = extraInfo;
                            options.url = url;

                            self.notifyFlashEditEffect(JSON.stringify(options));
                        }
                        break;
                    case 3:
                        var parent = $('#dlg_edit_animation');
                        var params = self.getParams(parent);

                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }
                        extraInfo = params;
                        id = params['id'];
                        url = params['url'];

                        delete extraInfo.myname;

                        extraInfo = JSON.stringify(extraInfo);
                        console.log(params);

                        updateData = {
                            id: id,
                            location: location,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };
                        break;
                    case 5:
                        var parent = $("#dlg_edit_cover");
                        var params = self.getParams(parent);
                        if (!Director.Util.verifyForm(params, type)) {
                            return;
                        }
                        extraInfo = params;
                        location = params['location_x'] + ',' + params['location_y'];

                        var size = {};
                        id = params['id'];
                        size.w = params['size_w'];
                        size.h = params['size_h'];
                        extraInfo.size = JSON.stringify(size);
                        url = "http://jyyunlou7.oss.qiyi.storage:8080/v1/AUTH_becf1c9cf362414992517833e5128e4e/20180103-05/yunpan/20180103/11/88/e009679b12974a11bfedc3638604f7b1.png";
                        // remove unnecessary params
                        delete extraInfo['location_x'];
                        delete extraInfo['location_y'];
                        delete extraInfo['size_w'];
                        delete extraInfo['size_h'];
                        delete extraInfo.id;

                        extraInfo = JSON.stringify(extraInfo);

                        updateData = {
                            id: id,
                            location: location,
                            extraInfo: extraInfo,
                            directorId: entity.id
                        };

                        if (id != '') {
                            var parent = $('#tabPanel_3');
                            var curDiv = parent.find("div[data-div-id=" + id + "]");
                            var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                            options.location = location;
                            options.extraInfo = extraInfo;
                            options.url = url;

                            self.notifyFlashEditEffect(JSON.stringify(options));
                        }

                        //console.log(params);
                        break;

                }

                if (id != '') {

                    Director.Dao.editEffect(updateData, function (data) {
                        if (data != null && data.code == "A00000") {
                            //EpgWeb.Plugin.showTips({content: "修改成功"});
                            self.refreshEffectList(self.type);
                        }
                    });

                } else {
                    var element = {};
                    element.directorId = entity.id;
                    element.programQipuId = entity.programQipuId;
                    element.url = url;
                    element.type = type;
                    element.location = location;
                    element.extraInfo = extraInfo;
                    if (type == 3) {
                        var parent = $('#dlg_edit_animation');
                        element.name = parent.find('input[name=myname]').val();

                    } else {
                        element.name = '';
                    }
                    element = JSON.stringify(element);

                    Director.Dao.addEffect({'data': element}, function (data) {
                        if (data != null && data.code == "A00000") {
                            Director.Util.refreshEffectList(type);
                        }
                    })
                }

                return true;
            },

            getParams: function (obj) {
                var self = this;
                var params = {};

                var $form = obj.find('form[name="basicForm"]');
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name;
                var key;
                $.each($elements, function () {
                    name = this.name;
                    if (name) {

                        if (this.type == 'radio') {
                            params[name] = $form.find('input[name="' + name + '"]:checked').val() || '';
                        } else if (this.type == 'checkbox') {
                            params[name] = $form.find('input[name="' + name + '"]').is(":checked") ? 1 : 0;
                        } else {
                            var value = $.trim($(this).val());
                            if (value == "0") {
                                params[name] = 0;
                            } else {
                                params[name] = parseInt(value) || value || '';
                            }

                        }
                    }

                });

                //params['id'] = $form.find('input[name=id]').val();

                console.log(params);

                return params;
            },

            checkValidStreamUrl: function (streamUrl, regRule) {
                return regRule.test(streamUrl)
            },
            updateResourceTitle: function (element) {
                var oldEntity = Director.Util.getEntity();
                var $input = $(element);
                var elementId = $input.attr("data-id");
                var isBackUp = $input.attr("data-backup") == "1";
                var pageBean = isBackUp ? Director.Config.PageBeanBackup : Director.Config.PageBeanResource;
                var signalName = $input.val().trim();
                var rowData = pageBean.findData("id", parseInt(elementId));
                if (signalName.length > 0) {
                    if (rowData.signalName == signalName) {
                        return;
                    }
                    Director.Dao.editResource({ id: elementId, signalName: signalName, directorId: oldEntity.id }, function (data) {
                        if (data != null && data.code == "A00000") {
                            //EpgWeb.Plugin.showTips({content: isBackUp ? "修改灾备成功" : "修改导播台资源成功"});
                            var rowData = pageBean.findData("id", parseInt(elementId));
                            rowData.signalName = $input.val().trim();
                            $input.val(signalName);
                        } else {
                            EpgWeb.Plugin.showTips({content: isBackUp ? "修改灾备失败" : "修改导播资源失败", type: "error"});
                        }
                    })
                } else {
                    $input.val(rowData.signalName);
                }
            },
            updateResourceTitleShortCut: function (event) {
                if (event.keyCode == 13) {
                    $(event.currentTarget).blur();
                }
            },

            updateEffectName: function (e) {
                var self = this;
                var entity = self.getEntity();
                var $input = $(e);
                var eid = $input.attr("data-id");
                var name = $input.val().trim();
                //重设data.name ,以便flash实时更新
                var $effectElement = $input.parent(".effect_element_div");
                var options = decodeURIComponent($effectElement.attr("data"));
                var optionsObject = JSON.parse(options);
                optionsObject.name = name;
                $effectElement.attr("data", encodeURIComponent(JSON.stringify(optionsObject)));

                Director.Dao.editEffect({id: eid, name: name, directorId: entity.id}, function (data) {
                    if (data != null && data.code == "A00000") {
                        //EpgWeb.Plugin.showTips({content: "修改成功"});
                        //self.refreshEffectList(self.type);
                    }
                });
            },

            updateEffectNameShortCut: function (event) {
                if (event.keyCode == 13) {
                    $(event.currentTarget).blur();
                }
            },

            delResource: function (element) {
                var entity = this.getEntity();
                var sendData = {id: $(element).attr("data-id"), directorId: entity.id };
                var isBackUp = $(element).attr("data-backup") == "1";
                SystemDialog.queryConfirm("确认要删除么？", function (flag) {
                    if (flag === true) {
                        Director.Dao.delResource(sendData, function (data) {
                            if (data != null && data.code == "A00000") {
                                EpgWeb.Plugin.showTips({content: isBackUp ? "删除灾备成功" : "删除导播台资源成功"});
                                if (isBackUp) {
                                    Director.Util.getBackUpList();
                                } else {
                                    Director.Util.getResourceList();
                                }
                            } else {
                                var result = "";
                                if (data != null) {
                                    if (data.data != null) {
                                        result = Director.Config.HINT_MSG["" + data.data];
                                        if (result == null) {
                                            result = '';
                                        }
                                    }
                                }
                                EpgWeb.Plugin.showTips({content: (isBackUp ? "删除灾备失败" : "删除导播资源失败") + (result.length > 0 ? "," + result : ""), type: "error"});
                            }
                        })
                    }
                })
            },

            delEffect: function (element, type) {
                var self = this;
                var entity = this.getEntity();
                var eid = $(element).attr("data-id");
                var sendData = {id: eid, directorId: entity.id};

                self.sendData = sendData;
                self.type = type;
                SystemDialog.queryConfirm("确定要删除么？", function (flag) {
                    if (flag === true) {
                        if (type == "4") {
                            var request = {};

                            request.type = 'get';
                            request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stopplay';
                            request.params = {
                                ID: eid,
                                PID: entity.programQipuId
                            };
                            request = JSON.stringify(request);
                            Ancestor.Dao.redirectRequest({request: request}, function (data) {
                                if (data != null && data.error_code == "A00000") {
                                    self.submitDelEffect(self.sendData, self.type);
                                } else {
                                    EpgWeb.Plugin.showTips({content: "删除失败 " + JSON.stringify(data), type: "error"});
                                }
                            });
                        } else if (type == "1" || type == "2" ||type == "5" ) {
                            var request = {};

                            request.type = 'get';
                            request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                            request.params = {
                                ID: eid,
                                PID: entity.programQipuId
                            };
                            request = JSON.stringify(request);
                            Ancestor.Dao.redirectRequest({request: request}, function (data) {
                                if (data != null && data.error_code == "A00000") {
                                    Director.Player.removeEffect(self.sendData.id);
                                    self.submitDelEffect(self.sendData, self.type);
                                } else {
                                    EpgWeb.Plugin.showTips({content: "删除失败 " + JSON.stringify(json), type: "error"});
                                }
                            });
                        } else {

                            Director.Dao.deleteEffect(sendData, function (data) {
                                if (data != null && data.code == "A00000") {
                                    EpgWeb.Plugin.showTips({content: "删除成功"});
                                    self.refreshEffectList(type);
                                } else {
                                    var result = '';
                                    if (data != null) {
                                        result = Director.Config.HINT_MSG["" + data.data];
                                        if (result == null) {
                                            result = '';
                                        }
                                    }
                                    EpgWeb.Plugin.showTips({content: "删除失败", type: "error"});
                                }
                            })
                        }
                    }
                })
            },

            submitDelEffect: function (sendData, type) {
                var self = this;
                Director.Dao.deleteEffect(sendData, function (data) {
                    if (data != null && data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: "删除成功"});
                        self.refreshEffectList(type);
                    } else {
                        var result = '';
                        if (data != null) {
                            result = Director.Config.HINT_MSG["" + data.data];
                            if (result == null) {
                                result = '';
                            }
                        }
                        EpgWeb.Plugin.showTips({content: "删除失败", type: "error"});
                    }
                })
            },

            setDefaultBackUp: function (element) {
                var oldEntity = Director.Util.getEntity();
                var elementId = $(element).attr("data-id");
                var elementData = Director.Config.PageBeanBackup.findData("id", parseInt(elementId));
                SystemDialog.queryConfirm("确认要设为默认灾备么？", function (flag) {
                    if (flag === true) {
                        Director.Config.WAITING_MSG = true;
                        Director.Dao.editResource({id: elementData.id, isDefaultBackup: 1, directorId: oldEntity.id}, function (data) {
                            if (data != null && data.code == "A00000") {
                                EpgWeb.Plugin.showTips({content: "设置成功"});
                                Director.Util.getBackUpList();
                            } else {
                                EpgWeb.Plugin.showTips({content: "设置失败", type: "error"});
                            }
                            Director.Config.WAITING_MSG = false;
                        })
                    }
                })
            },

            addBackUp: function () {
                var parent = $("#dlg_add_alternatePlay");
                parent.dialog("open");
                parent.find("label[name=hint-id]").html();
                var index = Director.Config.PageBeanBackup.getSource().length + 1;
                parent.find("input[name=signal_name]").val("备播视频" + index);
                if (parent.find("input[name=default_play]").is(":checked")) {
                    parent.find("input[name=default_play]").click();
                }
                parent.find("input[name=signal_url_1]").suggest("setValue", "");
            },
            addResource: function () {
                var parent = $("#dlg_add_signal");
                parent.dialog("open");
                parent.find("label[name=hint-id]").html();
                parent.find("select[name=signal_type]").change();
                var index = Director.Config.PageBeanResource.getSource().length + 1;
                parent.find("input[name=signal_name]").val("信号源" + index);
                parent.find("input[name=signal_url_2]").val("");
                parent.find("input[name=signal_url_0]").suggest("setValue", "");
                parent.find("input[name=signal_url_1]").suggest("setValue", "");
                parent.find("input[name=preview_url]").val("");
            },

            addEffect: function (element) {
                var self = this;
                var entity = self.getEntity();
                var params = element;
                params.directorId = entity.id;

                Director.Dao.addEffect(params, function (data) {
                    if (data != null && data.code == "A00000") {

                    }
                })
            },

            editEffectShow: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var parent = $('#tabPanel_3');
                var curDiv = parent.find("div[data-div-id=" + eid + "]");

                switch (type) {
                    case 1:
                        var parent = $("#dlg_edit_image");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};

                        extra.id = options.id;

                        if (options.location != '') {
                            var location = options.location.split(',');
                            extra.location_x = location[0];
                            extra.location_y = location[1];
                        } else {
                            extra.location_x = 0;
                            extra.location_y = 0;
                        }

                        if (extra.hasOwnProperty('size') && extra['size'] != '') {
                            var size = JSON.parse(extra.size);
                            extra.size_w = size.w;
                            extra.size_h = size.h;
                        }

                        parent.dialog("open");

                        parent.find('input[name=id]').val(eid);

                        $.each($elements, function () {
                            name = this.name;

                            var e = $(this);
                            if (name) {
                                if (this.type == 'checkbox') {
                                    e.prop("checked", extra[name] == 1);
                                } else if (name == "id") {

                                } else if (options.extraInfo == "" && e.attr("data-default")) {
                                    e.val(e.attr('data-default'));
                                } else {
                                    if (extra[name] === 0) {
                                        e.val(0);
                                    } else {
                                        e.val(extra[name] || '');
                                    }
                                }
                            }
                        });

                        if ($form.find('input[name=loop]').is(":checked")) {
                            $form.find('#effect-image-loop-div').show();
                        } else {
                            $form.find('#effect-image-loop-div').hide();
                        }

                        $form.find('select[name=animation]').change();

                        break;
                    case 2:
                        var parent = $("#dlg_edit_subtitle");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};

                        if (options.location != '') {
                            var location = options.location.split(',');
                            extra.location_x = location[0];
                            extra.location_y = location[1];
                        } else {
                            extra.location_x = 0;
                            extra.location_y = 0;
                        }

                        extra.content = options.url;


                        parent.dialog('option', 'title', '字幕编辑').dialog("open");

                        parent.find('input[name=id]').val(eid);
                        parent.find('textarea[name=content]').val(options.url);

                        $.each($elements, function () {
                            name = this.name;
                            var e = $(this);

                            if (name) {
                                if (this.type == 'checkbox') {
                                    e.prop("checked", extra[name] == 1);
                                } else if (name == "id") {

                                } else {
                                    if (extra[name] == "0") {
                                        e.val(extra[name]);
                                    } else {
                                        e.val(extra[name] || '');
                                    }
                                }
                            }
                        });

                        var fontElements = ['fontBold'];
                        $.each(fontElements, function (index, e) {
                            if (extra[e] == "1") {
                                $form.find('a.' + e).addClass('active');
                            } else {
                                $form.find('a.' + e).removeClass('active');
                            }

                            //var d = $form.find('a.' + e);
                            //var $input = $form.find('input.' + e);
                            //d.bind('click',{d: d, input: $input}, function(event) {
                            //    if (event.data.d.hasClass('active')) {
                            //        event.data.d.removeClass('active');
                            //        event.data.input.val(0);
                            //    }else{
                            //        event.data.d.addClass('active');
                            //        event.data.input.val(1);
                            //    }
                            //})
                        });

                        if ($form.find('input[name=loop]').is(":checked")) {
                            $form.find('#effect-subtitle-loop-div').show();
                        } else {
                            $form.find('#effect-subtitle-loop-div').hide();
                        }

                        if ($form.find('input[name=horseLamp]').is(":checked")) {
                            $form.find('#effect-subtitle-loop-container-div').show();
                        } else {
                            $form.find('#effect-subtitle-loop-container-div').hide();
                        }

                        Director.Util.dialogSubtitlePreview();

                        break;
                    case 3:
                        var parent = $("#dlg_edit_animation");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};
                        parent.dialog('option', 'title', '编辑').dialog("open");

                        parent.find('input[name=id]').val(eid);
                        parent.find('div#form_animation_url').hide();

                        $.each($elements, function () {
                            name = this.name;
                            var e = $(this);

                            if (name) {
                                if (this.type == 'checkbox') {
                                    e.prop("checked", extra[name] == 1);
                                } else if (name == "id") {

                                } else {
                                    if (extra[name] == "0") {
                                        e.val(extra[name]);
                                    } else {
                                        e.val(extra[name] || '');
                                    }
                                }
                            }
                        });

                        if ($form.find('input[name=loop]').is(":checked")) {
                            $form.find('#effect-animation-loop-div').show();
                        } else {
                            $form.find('#effect-animation-loop-div').hide();
                        }
                        break;
                    case 5:
                        var parent = $("#dlg_edit_cover");
                        var $form = parent.find('form[name="basicForm"]');
                        var $elements = $.makeArray($form.prop('elements')).filter(function () {
                            return true; //this.name;
                        });
                        var options = JSON.parse(decodeURIComponent($(curDiv).attr('data')));
                        var extra = options.extraInfo != "" ? JSON.parse(options.extraInfo) : {};

                        console.log("elements: " + JSON.stringify($elements));
                        extra.id = options.id;
                        if (options.location != '') {
                            var location = options.location.split(',');
                            extra.location_x = location[0];
                            extra.location_y = location[1];
                        } else {
                            extra.location_x = 0;
                            extra.location_y = 0;
                        }

                        if (extra.hasOwnProperty('size') && extra['size'] != '') {
                            var size = JSON.parse(extra.size);
                            extra.size_w = size.w;
                            extra.size_h = size.h;
                        }
                        parent.dialog("open");
                        parent.find('input[name=id]').val(eid);
                        $.each($elements, function () {
                            name = this.name;

                            var e = $(this);
                            if (name) {
                                if (extra[name] === 0) {
                                    e.val(0);
                                } else {
                                    e.val(extra[name] || '');
                                }
                            }
                        });
                        break;

                }
            },

            AddSubtitleBackground: function (data, params) {
                var parent = $("#dlg_edit_subtitle");
                var $background = parent.find('input[name=background]');
                $background.val(data.httpInnerUrl);
            },

            AddAnimationUrl: function (data, params) {
                var parent = $("#dlg_edit_animation");
                var $background = parent.find('input[name=url]');
                var myname = parent.find('input[name=myname]');
                $background.val(data.httpInnerUrl);
                myname.val(params.file.name);
            },

            clearForm: function (form) {
                var $form = form;
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                //var fontElements = ['fontBold', 'fontItalic', 'fontUnderline'];
                var fontElements = ['fontBold'];

                $form.find('input[name=id]').val('');
                $form.find('textarea[name=content]').val('');

                $.each($elements, function () {
                    name = this.name;

                    var e = $(this);
                    if (name) {
                        if (this.type == 'checkbox') {
                            e.prop("checked", false);
                        } else if (name == "id") {

                        } else if (e.attr("data-default")) {
                            e.val(e.attr('data-default'));
                        } else {
                            e.val('');
                        }
                    }

                    if ($.inArray(name, fontElements) != -1) {
                        $form.find('a.' + name).removeClass('active');
                    }
                    ;


                });

            },

            AddAnimationForeground: function (data, params) {
                var parent = $("#dlg_edit_animation");
                var $background = parent.find('input[name=foreground]');
                $background.val(data.httpInnerUrl);
            },

            AddSubtitleShow: function () {
                var self = this;
                var parent = $("#dlg_edit_subtitle");
                var $form = parent.find('form[name="basicForm"]');
                self.clearForm($form);
                parent.dialog('option', 'title', '添加字幕').dialog("open");


                if ($form.find('input[name=loop]').is(":checked")) {
                    $form.find('#effect-subtitle-loop-div').show();
                } else {
                    $form.find('#effect-subtitle-loop-div').hide();
                }

                if ($form.find('input[name=horseLamp]').is(":checked")) {
                    $form.find('#effect-subtitle-loop-container-div').show();
                } else {
                    $form.find('#effect-subtitle-loop-container-div').hide();
                }

                $form.find('select[name=fontSize]').val("15");


                Director.Util.dialogSubtitlePreview();
            },

            AddAnimationShow: function () {
                var self = this;
                var parent = $("#dlg_edit_animation");
                var $form = parent.find('form[name="basicForm"]');
                self.clearForm($form);
                parent.dialog('option', 'title', '添加动画').dialog("open");

                $form.find('#form_animation_url').show();

                if ($form.find('input[name=loop]').is(":checked")) {
                    $form.find('#effect-animation-loop-div').show();
                } else {
                    $form.find('#effect-animation-loop-div').hide();
                }
            },
            AddCoverShow: function () {
                var self = this;
                //获取当前数据是否大于最大数量8
                var effectCoversLength = $("#effect-covers").children().length -1;
                if (effectCoversLength >= 8) {
                    EpgWeb.Plugin.showTips({content: "最多同时支持8个遮标", type: "error"});
                }else{
                    var parent = $("#dlg_edit_cover");
                    var $form = parent.find('form[name="basicForm"]');
                    self.clearForm($form);
                    parent.dialog('option', 'title', '遮标编辑').dialog("open");
                }


            },

            startUploadFile: function (params, callback) {
                var self = this;
                var url = Director.Config.EFFECT_UPLOAD_URL;
                url = url + "?t=1";

                $.each(params, function (k, v) {
                    url = url + "&" + k + "=" + v;
                });

                $.ajax({
                    url: url,
                    method: "post",
                    cache: false,
                    contentType: false,
                    processData: false,
                    xhr: function () {
                        var xhr = jQuery.ajaxSettings.xhr();
                        return xhr;
                    },
                    data: params.file,
                    success: function (data) {
                        if (data.code == "A00000") {
                            console.log("success upload");
                            callback.call(this, data.data, params);
                        }
                    },
                    error: function (data) {

                    }
                })
            },

            getEntity: function () {
                var responseData = Director.Dao.getDataByName("entity");
                if (responseData == null || responseData.data == null || responseData.data.totalCount == 0) {
                    return null;
                }
                return responseData.data.result[0];
            },
            reloadEntity: function (needNotify) {
                var self = this;
                var entity = self.getEntity();
                Director.Dao.getDirector({qipuId: entity.programQipuId, fullMode: "true"}, function (data) {
                    if (data != null && data.code == "A00000") {
                        if (data.data.result.length == 1) {
                            Director.Util.updateEntity(data);
                            entity = self.getEntity();
                            console.log(" reloadEntity :" + JSON.stringify(entity));
                            Director.Player.setCurResourceId(entity.resourceId);
                            if (needNotify) {
                                Director.Player.notifyPlayingChange();
                            }
                        }
                    }
                });
            },
            updateEntity: function (newResponse) {
                EpgWeb.ajaxQueue.removeTask("entity");
                EpgWeb.ajaxQueue.push("entity", null, newResponse);
                console.log("更新 entity 完成数据");
            },
            preSetMainResource: function (resourceList) {
                var self = this;
                var entity = self.getEntity();
                $.each(resourceList, function (i, element) {
                    if (element.signalType == 0 || element.signalType == 2) {
                        if(element.id == entity.mainResourceId) {
                            element.isMainResource = true;
                        } else {
                            element.isMainResource = false;
                        }
                    }
                });
            },
            getResourceList: function () {
                var entity = this.getEntity();
                var self = this;
                Director.Dao.getResourceList({directorId: entity.id, isBackup: 0}, function (data) {
                    Director.Config.PageBeanResource.setNewData([], 10);
                    if (data != null && data.code == "A00000") {
                        self.preSetMainResource(data.data);
                        Director.Config.PageBeanResource.setNewData(data.data);
                        Director.Player.registerResource(data.data);
                    }
                })
            },
            getBackUpList: function (autoHandler) {
                var entity = this.getEntity();
                var self = this;
                Director.Dao.getResourceList({directorId: entity.id, isBackup: 1}, function (data) {
                    Director.Config.PageBeanBackup.setNewData([], 10);
                    if (data != null && data.code == "A00000") {
                        Director.Config.PageBeanBackup.setNewData(data.data)
                        Director.Player.registerBackup(data.data);
                    }
                })
            },


            getEffectList: function (type) {
                var self = this;
                var entity = this.getEntity();

                Director.Dao.getEffectList({directorId: entity.id, type: type}, function (data) {
                    if (data != null && data.code == "A00000") {
                        self.makeEffectList(type, data.data);

                        switch (type) {
                            case 1:
                                Director.Config.PageBeanEffectImage.setNewData(data.data);
                                Director.Util.bindEffectImageEvent();
                                break;
                            case 2:
                                Director.Config.PageBeanEffectSubtitle.setNewData(data.data);
                                break;
                            case 3:
                                Director.Config.PageBeanEffectAnimation.setNewData(data.data);
                                break;
                            case 4:
                                Director.Config.PageBeanEffectAudio.setNewData(data.data);
                                Director.Util.bindEffectAudioEvent();
                                break;
                            case 5:
                                Director.Config.PageBeanEffectCover.setNewData(data.data);
                                break;

                        }
                    }
                })

            },

            makeEffectList: function (type, data) {
                var self = this;

                var container = null,
                    content = "";

                var htmlArr = [];

                switch (type) {
                    case 1:
                        container = $("#effect-images");
                        break;
                    case 2:
                        container = $("#effect-subtitles");
                        break;
                    case 3:
                        container = $("#effect-animations");
                        break;
                    case 4:
                        container = $("#effect-audios");
                        break;
                    case 5:
                        container = $("#effect-covers");
                        break;

                }
                if(type == 5) {
                    $.each(data, function (index, e) {
                        htmlArr.unshift(self.makeUpEffectDiv(e, type));
                    });
                }else{

                    $.each(data, function (index, e) {
                        htmlArr.push(self.makeUpEffectDiv(e, type));
                    });
                }

                htmlArr.push(self.makeUpEffectAddDiv(type));

                content = htmlArr.join('');

                container.html(content);
            },

            refreshEffectList: function (type) {
                var self = this;

                //switch (type) {
                //    case 1:
                //        $("#effect-images").html('');
                //        break;
                //    case 2:
                //        $("#effect-subtitles").html('');
                //        break;
                //    case 3:
                //        $("#effect-animations").html('');
                //        break;
                //    case 4:
                //        $("#effect-audios").html('');
                //        break;
                //}

                self.getEffectList(type);
            },

            initDefaultBackupZone: function () {
                var self = this;
                var htmlArr = [];
                htmlArr.push(self.makeUpBackUpAddDiv());
                $("#tabPanel_child_2").html(htmlArr.join(""));
            },
            initDefaultResourceZone: function () {
                var self = this;
                var htmlArr = [];
                htmlArr.push(self.makeUpResourceAddDiv());
                $("#tabPanel_child_1").html(htmlArr.join(""));
            },

            initDetailZone: function (entity) {
                Director.Model.initDetail(entity)
            },

            doResourceSwitch: function (resourceId, time, playCounts) {
                var entity = Director.Util.getEntity();
                Director.Dao.switchResource({id: resourceId, directorId: entity.id, time: time, playCounts: playCounts}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.reloadEntity(true);
                    } else if (data != null && data.code == "A00001") {
                        EpgWeb.Plugin.showTips({content: data.msg, type: "error"});
                        Director.Util.reloadEntity(false);
                    }
                })
            },
            switchBackUp: function () {
                if (Director.Config.WAITING_MSG) {
                    SystemDialog.queryAlert("正在处理中，请稍后操作");
                    return;
                }
                var btnTarget = $("button[name=changeBtn]");
                btnTarget.prop("disabled", "disabled");
                var entity = Director.Util.getEntity();
                if (entity != null) {
                    Director.Config.WAITING_MSG = true;
                    Director.Dao.switchBackUp({directorId: entity.id}, function (data) {
                        if (data != null && data.code == "A00000") {
                            EpgWeb.Plugin.showTips({content: "切换成功"});
                            Director.Dao.cfgName.oldDelay = entity.delay;
                            Director.Util.reloadEntity(true);
//                            btnTarget.attr("data-key", "recoverDelay");
//                            btnTarget.html("恢复延时");
                        } else {
                            var msgPlus = null;
                            if (data != null && data.msg != null) {
                                msgPlus = data.msg
                            }
                            EpgWeb.Plugin.showTips({content: "切换失败;" + msgPlus, type: "error"});
                        }
                        btnTarget.removeAttr("disabled", "disabled");
                        Director.Config.WAITING_MSG = false;
                    });
                }
            },
//            recoverDelay: function () {
//                var btnTarget = $("button[name=changeBtn]");
//                btnTarget.prop("disabled", "disabled");
//                var entity = Director.Util.getEntity();
//                if (Director.Dao.cfgName.oldDelay > 0 && Director.Dao.cfgName.oldDelay != entity.delay) {
//                    var newData = $.extend({}, entity)
//                    newData.delay = Director.Dao.cfgName.oldDelay;
//                    Director.Dao.editDirector({entity: JSON.stringify(newData)}, function (data) {
//                        if (data != null && data.code == "A00000") {
//                            EpgWeb.Plugin.showTips({content: "恢复延时成功"});
//                            Director.Util.reloadEntity(false);
//                            Director.Dao.cfgName.oldDelay = -1;
//                            btnTarget.attr("data-key", "switchBackUp");
//                            btnTarget.html("切换灾备");
//                        } else {
//                            var msgPlus = null;
//                            if (data != null && data.msg != null) {
//                                msgPlus = data.msg
//                            }
//                            EpgWeb.Plugin.showTips({content: "恢复延时失败;" + msgPlus, type: "error"});
//                        }
//                        btnTarget.removeAttr("disabled", "disabled");
//                    });
//                } else {
//                    btnTarget.attr("data-key", "switchBackUp");
//                    btnTarget.html("切换灾备");
//                    btnTarget.removeAttr("disabled", "disabled");
//                }
//            },
            changeTab: function (element, cur) {
                var elementDom = $(element);
                if (elementDom.hasClass("selected")) {
                    return;
                }
                $("#tabsDiv").find("li").removeClass("selected").addClass("unselected");
                $("#tabsDiv").find("a").removeClass("selected").addClass("unselected");
                elementDom.removeClass("unselected").addClass("selected");
                elementDom.parent().removeClass("unselected").addClass("selected");

                var refIds = elementDom.attr("data-id").split(",");
                $("#" + refIds[0]).css({zIndex: 1, top: 0, left: 0});
                $("#" + refIds[1]).css({zIndex: -8, top: "-1999px", left: "-1999px"});
                $("#" + refIds[2]).css({zIndex: -9, top: "-2999px", left: "-2999px"});
                $("#" + refIds[3]).css({zIndex: -10, top: "-3999px", left: "-3999px"});

                var toPlayArr = $("#" + refIds[0]).find("object");
                var toStopArr = $("#" + refIds[1]).find("object");
                var toStopArr2 = $("#" + refIds[2]).find("object");
                var toStopArr3 = $("#" + refIds[3]).find("object");

                if (toPlayArr.length > 0 && refIds[0] != "tabPanel_3") {
                    $.each(toPlayArr, function (i, flashPlayer) {
                        Director.Player.recoverVol(flashPlayer.id);
                    })
                }
                if (toStopArr.length > 0 && refIds[1] != "tabPanel_3") {
                    $.each(toStopArr, function (i, flashPlayer) {
                        Director.Player.stopVol(flashPlayer.id);
                    })
                }
                if (toStopArr2.length > 0 && refIds[2] != "tabPanel_3") {
                    $.each(toStopArr2, function (i, flashPlayer) {
                        Director.Player.stopVol(flashPlayer.id);
                    })
                }
                if (toStopArr3.length > 0 && refIds[3] != "tabPanel_3") {
                    $.each(toStopArr2, function (i, flashPlayer) {
                        Director.Player.stopVol(flashPlayer.id);
                    })
                }

                if (refIds[0] == "tabPanel_4") {
                    Director.Commentary.refreshCommentaryList(false);
                }else{
                    Director.Commentary.clearCommentaryList();
                }
            },
//            releaseAllDirector: function () {
//                var entity = Director.Util.getEntity();
//                if (entity != null) {
//                    Director.Dao.releaseAllDirector({directorId: entity.id}, function (data) {
//                        if (data != null && data.code == "A00000") {
//                            EpgWeb.Plugin.showTips({content: "releaseAllDirector 成功"});
//                            setTimeout(function () {
//                                window.location.href = "/epg/program_director_list.html";
//                            }, 1500)
//                        } else {
//                            EpgWeb.Plugin.showTips({content: "releaseAllDirector 失败", type: "error"});
//                        }
//                    })
//                }
//            },
            delDirector: function (directorId) {
                SystemDialog.queryConfirm("确认要删除么？", function (flag) {
                    if (flag === true) {
                        Director.Dao.releaseAllDirector({directorId: directorId}, function (data) {
                            if (data != null && data.code == "A00000") {
                                EpgWeb.Plugin.showTips({content: "删除 成功"});
                                $("#list").trigger('reloadGrid');
                            } else {
                                EpgWeb.Plugin.showTips({content: "删除 失败", type: "error"});
                            }
                        })
                    }
                })
            },

            showToolTip: function (element) {
                if (element.value.length > 0) {
                    element.title = element.value;
                }
            },
            resizeTextWidth: function (text, maxLength) {
                var spanTarget = $("span[name=adjTextLength]");

                spanTarget.html(text);
                var newLength = parseInt(text.length * maxLength / spanTarget.width());
                spanTarget.html(text.substring(0, newLength) + "...");
                while (spanTarget.width() > maxLength) {
                    newLength--;
                    spanTarget.html(text.substring(0, newLength) + "...");
                }
                return spanTarget.html();
            },
            showTipsResourceId: function (element) {
                element.title = "资源ID:" + $(element).attr("data-id");
            },

            changeVolumn: function (element) {
                var self = this;
                var volumn = $(element).val();
                var extraInfo = {};
                var entity = self.getEntity();
                if (volumn == "0") {
                    extraInfo.volumn = 0;
                } else {
                    extraInfo.volumn = parseInt(volumn) || volumn;
                }
                extraInfo = JSON.stringify(extraInfo);

                var id = $(element).attr('data-id');
                Director.Dao.editEffect({id: id, extraInfo: extraInfo, directorId: entity.id}, function(data) {
                    if (data != null && data.code == "A00000") {
                        //EpgWeb.Plugin.showTips({content: "修改成功"});
                    }
                })
            },
            changeColor: function (e) {
                console.log(e.value);
            },

            playEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();

                if (Director.Config.EFFECT_CTRL_KEYDOWN) {
                    console.log(eid + " ctrl");
                    Director.Dao.editEffect({id: eid, directorId: entity.id, status: "1"}, function (data) {
                        self.refreshEffectList(type);
                    })

                } else {
                    console.log(eid + " click");
                }
            },

            submitPlayEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();
                var options = {};

                options.eid = eid;
                options.pid = entity.programQipuId;
                options.type = type;
                options.status = "1";
                options.did = entity.id;

                if (type == 4) {
                    self.notifyStopPlayEffect(options, function (options) {
                        setTimeout(function () {
                            self.notifyPlayEffect(options, self.saveEffectStatus);
                        }, 100);
                    })
                } else {
                    self.notifyPlayEffect(options, self.saveEffectStatus);
                }

            },

            saveEffectStatus: function (options) {
                var self = this;
                var entity = self.getEntity();

                Director.Dao.editEffect({id: options.eid, directorId: entity.id, status: options.status}, function (data) {
                    self.refreshEffectList(options.type);
                })
            },

            notifyPlayEffect: function (options, callback) {
                var self = this;
                self.callback = callback;
                self.options = options;
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'startplay';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };
                request.directorId = options.did;
                request.logType = "114";

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {

                    self.callback(options);
                })

            },

            stopPlayEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();

                Director.Dao.editEffect({id: eid, directorId: entity.id, status: "0"}, function(data) {
                    self.refreshEffectList(type);
                })

            },

            submitStopPlayEffect: function (e, type) {
                var self = this;
                var eid = $(e).attr('data-id');
                var entity = self.getEntity();
                var options = {};

                options.eid = eid;
                options.pid = entity.programQipuId;
                options.type = type;
                options.status = "0";
                options.did = entity.id;

                //self.notifyStopPreviewEffect(options, function(options){});
                self.notifyStopPlayEffect(options, self.saveEffectStatus);

            },

            notifyStopPlayEffect: function (options, callback) {
                var self = this;
                self.callback = callback;
                self.options = options;
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stopplay';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };
                request.directorId = options.did;
                request.logType = "115";

                request = JSON.stringify(request);
                Director.Dao.redirectApi({request: request}, function (json) {
                    self.callback(options);
                })
            },

            notifyStopPreviewEffect: function (options, callback) {
                var self = this;
                self.callback = callback;
                self.options = options;
                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                request.params = {
                    ID: options.eid,
                    PID: options.pid
                };
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request}, function (json) {
                    self.callback(options);
                })
            },

            notifyStopPreviewEffectByFlash: function (id) {
                var self = this;
                var entity = self.getEntity();

                var request = {};

                request.type = 'get';
                request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                request.params = {
                    ID: id,
                    PID: entity.programQipuId
                };
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request}, function (json) {
                })
            },
            notifySetResourcePlayCounts: function (data) {
                var self = this;
                var request = {};
                if (data != null && data.resourceId != null && data.num != null) {
                    request.id = data.resourceId;
                    request.playCounts = data.num;
                    Director.Dao.setResourcePlayCounts({id: data.resourceId, playCounts: data.num}, function (json) {

                    });
                }

            },

            isValidImage: function (filetype) {
                return $.inArray(filetype.toLowerCase(), ["png", "jpg", "bmp", "gif"]) >= 0;
            },

            isValidVideo: function (filetype) {
                return $.inArray(filetype.toLowerCase(), ["mov"]) >= 0;
            },

            isValidAudio: function (filetype) {
                return $.inArray(filetype.toLowerCase(), ["mp3"]) >= 0;
            },

            previewEffect: function (e) {
                var self = this;
                var eid = $(e).attr('data-id');
                var parent = $('#tabPanel_3');
                var curDiv = parent.find("div[data-div-id=" + eid + "]");
                var data = decodeURIComponent($(curDiv).attr('data'));
                Director.Player.addEffect(data);

                var btn = $('#effectBtnEdit');
                var isEditing = btn.attr('data-is-editing');
                if (isEditing == "0") {
                    btn.text("预览");
                    btn.attr('data-is-editing', "1");
                }

            },

            previewAnimationEffect: function (e) {
                var self = this;
                var eid = $(e).attr('data-id');

                var updateData = {
                    id: eid,
                    isPreview: 1
                };

                Director.Dao.editEffect(updateData, function (data) {
                    if (data != null && data.code == "A00000") {
                        //EpgWeb.Plugin.showTips({content: "预览成功", type: "success"});
                    } else {
                        EpgWeb.Plugin.showTips({content: "预览失败", type: "error"});
                    }
                });

            },

            closePreviewEffectReset: function () {
                Director.Player.closeEditEffect(0);

                var btn = $('#effectBtnEdit');
                var isEditing = btn.attr('data-is-editing');

                if (isEditing == "1") {
                    btn.text("编辑");
                    btn.attr('data-is-editing', "0");
                }
            },

            editPreviewEffectSwitch: function (e) {
                var btn = $(e);
                var isEditing = btn.attr('data-is-editing');

                if (isEditing == "0") {
                    Director.Player.openEditEffect();
                    btn.text("预览");
                    btn.attr('data-is-editing', "1");
                } else {
                    Director.Player.closeEditEffect(1);
                    btn.text("编辑");
                    btn.attr('data-is-editing', "0");
                }

            },

            notifyFlashEditEffect: function (e) {
                Director.Player.editEffect(e);
            },

            batchStopPreview: function (data, handler) {
                console.log('batchStopPreview ' + data)
                var self = this;
                var dataList = JSON.parse(data);
                var dataArr = [];
                var requestData = null;
                var entity = self.getEntity();
                var currentTime = Date.now();

                $.each(dataList, function (i, element) {
                    requestData = {
                        url: Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview',
                        type: 'get',
                        params: {
                            ID: element.id,
                            PID: entity.programQipuId
                        }
                    };
                    dataArr.push({'request': JSON.stringify(requestData), timeSign: currentTime});
                });

                var task = {
                    regName: "stopPreview",
                    options: {
                        url: '/api/redirect',
                        dataType: 'json',
                        type: 'post'
                    },
                    handler: function (options) {
                        console.log(options.acceptArr);

                        handler.call(this, data);
                    }
                };


                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                EpgWeb.ajaxQueue.startLoad();
            },

            batchStartPreview: function (data, handler) {
                console.log('batchStartPreview ' + data)
                var self = this;
                var dataList = JSON.parse(data);
                var dataArr = [];
                var requestData = null;
                var entity = self.getEntity();
                var currentTime = Date.now();

                $.each(dataList, function (i, element) {
                    requestData = {
                        url: Director.Config.EFFECT_BACNEND_URL_PREFIX + 'startpreview',
                        type: 'get',
                        params: {
                            ID: element.id,
                            PID: entity.programQipuId
                        }
                    };
                    dataArr.push({'request': JSON.stringify(requestData), timeSign: currentTime});
                });

                var task = {
                    regName: "startPreview",
                    options: {
                        url: '/api/redirect',
                        dataType: 'json',
                        type: 'post'
                    },
                    handler: function (options) {
                        console.log(options.acceptArr);

                        handler.call(this, data);
                    }
                };


                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                EpgWeb.ajaxQueue.startLoad();
            },

            batchEditEffect: function (data, handler) {
                //console.log('batchEditEffect ' + data)
                var self = this;
                var dataList = JSON.parse(data);
                var dataArr = [];
                var requestData = null;
                var entity = self.getEntity();
                var currentTime = Date.now();
                var updateData = null;
                $.each(dataList, function (i, element) {
                    element.extraInfo.size = JSON.stringify(element.extraInfo.size);
                    updateData = {
                        id: element.id,
                        location: element.location,
                        extraInfo: JSON.stringify(element.extraInfo),
                        directorId: entity.id,
                        isPreview: 1
                    };
                    dataArr.push(updateData);
                });

                var task = {
                    regName: "editEffect",
                    options: {
                        url: Director.urlConfig.effectEditUrl,
                        dataType: 'json',
                        type: 'post'
                    },
                    handler: function (options) {
                        console.log(options.acceptArr);
                        handler.call(this, data);
                    }
                };
                console.log("" + EpgWeb.ajaxQueue.isRunning());
                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                EpgWeb.ajaxQueue.startLoad();
            },

            submitPreviewAllEffects: function (data) {
                var self = this;
                var actionNext = function () {
                    $(document).dequeue("previewEffects");
                };

                var dataList = JSON.parse(data);

                var actions = [];
                var entity = self.getEntity();

                $.each(dataList, function (i, element) {

                    // edit effect
                    actions.push(function () {
                        element.extraInfo.size = JSON.stringify(element.extraInfo.size);
                        var updateData = {
                            id: element.id,
                            location: element.location,
                            extraInfo: JSON.stringify(element.extraInfo),
                            directorId: entity.id,
                            isPreview: 1
                        };

                        Director.Dao.editEffect(updateData, function (data) {
                            if (data != null && data.code == "A00000") {
                                actionNext();
                            } else {
                                console.log('failed ' + data);
                            }
                        });
                    });

                    // stop preview
                    //actions.push(function() {
                    //    var request = {};
                    //
                    //    request.type = 'get';
                    //    request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'stoppreview';
                    //    request.params = {
                    //        ID: element.id,
                    //        PID: entity.programQipuId
                    //    };
                    //    request = JSON.stringify(request);
                    //    Ancestor.Dao.redirectRequest({request: request}, function(json) {
                    //        actionNext();
                    //    })
                    //})
                    //
                    //// start Preview
                    //actions.push(function() {
                    //    var request = {};
                    //
                    //    request.type = 'get';
                    //    request.url = Director.Config.EFFECT_BACNEND_URL_PREFIX + 'startpreview';
                    //    request.params = {
                    //        ID: element.id,
                    //        PID: entity.programQipuId
                    //    };
                    //    request = JSON.stringify(request);
                    //    Ancestor.Dao.redirectRequest({request: request}, function(json) {
                    //        actionNext();
                    //    })
                    //})
                })

                actions.push(function () {
                    Director.Util.refreshEffectList(1);
                    Director.Util.refreshEffectList(2);
                    Director.Util.refreshEffectList(5);
                })


                $(document).queue("previewEffects", actions);
                actionNext();

            },

            dialogSubtitlePreview: function () {
                var parent = $('#dlg_edit_subtitle');
                var content = parent.find("textarea[name=content]");
                var fontName = parent.find('select[name=fontName]');
                var fontSize = parent.find('select[name=fontSize]');
                var fontColor = parent.find('input[name=fontColor]');
                var fontBold = parent.find('input[name=fontBold]');

                var styles = {
                    "font-family": fontName.find('option:selected').text(),
                    "font-size": fontSize.val() + "px",
                    "line-height": fontSize.val() + "px",
                    "font-weight": fontBold.val() == "1" ? "bold" : "normal",
                    "color": fontColor.val()
                }

                content.css(styles);

            },

            textLimit: function (e, limit, isNewline) {
                //if($(e).val().length > limit) {
                //    $(e).val($(e).val().substring(0, limit));
                //}
                console.log(e);
            },

            verifyForm: function (data, type) {
                var self = this;
                var checkArr = [];
                switch (type) {
                    case 1:
                        checkArr.push({value: [data.enterDuration, data.stayDuration, data.exitDuration, data.location_x, data.location_y],
                            error: ["进入时间只能为非负整数", "停留时间只能为非负整数", "退出时间只能为非负整数", "坐标只能为非负整数", "坐标只能为非负整数"], type: "number"});
                        checkArr.push({value: data.size_w, error: "大小为数字", type: "number"});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "le", other: 640});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "ge", other: 2});
                        if (data.loop == 1) {
                            checkArr.push({value: data.interval, error: "间隔时间只能为非负整数", type: "number"});
                            checkArr.push({value: data.playTimes, error: "播放次数必须大于0", type: "positive"});
                        }
                        break;
                    case 2:
                        checkArr.push({value: data.content, error: "请输入字幕内容", type: "not_empty"});
                        checkArr.push({value: Com.string.getStrLength(data.content), error: "字幕内容不能超过200个字", type: "le", other: 400});
                        checkArr.push({value: [data.location_x, data.location_y], error: "坐标只能为非负整数", type: "number"});
                        if (data.loop == 1) {
                            checkArr.push({value: data.interval, error: "间隔时间只能为非负整数", type: "number"});
                            checkArr.push({value: data.playTimes, error: "播放次数必须大于0", type: "positive"});
                        }
                        break;
                    case 3:
                        checkArr.push({value: data.url, error: "请上传动画", type: "not_empty"});
                        if (data.loop == 1) {
                            checkArr.push({value: data.interval, error: "间隔时间只能为非负整数", type: "number"});
                            checkArr.push({value: data.playTimes, error: "播放次数必须大于0", type: "positive"});
                        }
                        break;
                    case 5:
                        checkArr.push({value: [data.location_x, data.location_y],
                            error: ["坐标只能为非负整数", "坐标只能为非负整数"], type: "number"});
                        checkArr.push({value: data.size_w, error: "大小为数字", type: "number"});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "le", other: 640});
                        checkArr.push({value: data.size_w, error: "大小只能是2到640之间的数值", type: "ge", other: 2});
                        break;
                }
                if (checkArr.length > 0) {
                    return EpgWeb.Plugin.Validate.batchCheck(checkArr);
                }
                return true;
            },

            dataIsNumber: function (value) {
                return !isNaN(value)
            },

            strlen: function (str) {
                var len = 0;
                for (var i = 0; i < str.length; i++) {
                    var c = str.charCodeAt(i);
                    //单字节加1
                    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                        len++;
                    }
                    else {
                        len += 2;
                    }
                }
                return len;
            },

            isValidImageWidthHeight: function (url) {
                var image = new Image();
                image.onload = function () {
                    alert(image.width);
                }

                image.src = url;
                return false;

            },
            quickCreatePreviewUrl: function () {
                var parent = $("#dlg_add_signal");
                var signalUrl = parent.find("input[name=signal_url_2]").val();
                if (!this.checkValidStreamUrl(signalUrl, Director.Config.REG_VALIDATE.HTTP_RTMP_UDP)) {
                    EpgWeb.Plugin.showTips({content: "流地址格式错误,需要( rtmp://或udp://或http://)", type: "error"});
                    return false;
                }
                parent.find("button[name=query_system_preview_url]").prop("disabled", "disabled");
                parent.find("input[name=preview_url]").val("");
                parent.find("input[name=preview_url]").prop("readonly", true);
                Director.Dao.quickCreatePreviewUrl({url: signalUrl }, function (data) {
                    parent.find("input[name=preview_url]").removeAttr("readonly");
                    parent.find("button[name=query_system_preview_url]").removeAttr("disabled");
                    if (data != null && data.code == "A00000") {
                        parent.find("input[name=preview_url]").val(data.data)
                    } else {
                        parent.find("input[name=preview_url]").val("error happened")
                    }
                });
            },

            bindEffectImageEvent: function () {
                var self = this;
                var $imageArea = $("#effect-tabs-1");
                //$subtitleArea = $("#effect-tabs-2"),
                //$animationArea = $("#effect-tabs-3"),
                //$audioArea = $("#effect-tabs-4");

                var $imageUploadBtn = $imageArea.find("input.uploadBtn");
                var imageParent = $("#dlg_edit_image");
                $imageUploadBtn.val("");
                $imageUploadBtn.bind("click", function (event) {
                    console.log("click");
                });
                $imageUploadBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = Director.Config.EffectUploadCommonParams;

                    params.business_type = "image";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是图片
                    if (!Director.Util.isValidImage(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传图片格式只支持png, jpg, bmp, gif, 请重新上传", type: "error"})
                        return;
                    }


                    self.startUploadFile(params, self.AddEffectImage);

                });
            },

            bindEffectAudioEvent: function() {
                var self = this;
                var $audioArea = $("#effect-tabs-4");

                var $audioUploadBtn = $audioArea.find("input.uploadBtn");
                $audioUploadBtn.val('');
                $audioUploadBtn.bind("click", function (event) {
                    console.log("click");
                });
                $audioUploadBtn.bind("change", function (e) {
                    var file = e.target.files[0];
                    var url = Com.file.getObjectURL(file)

                    var params = Director.Config.EffectUploadCommonParams;

                    params.business_type = "audio";
                    params.file_type = Com.file.getExt(file.name);
                    params.file_size = file.size;

                    params.file = file;

                    $(this).val('');
                    // 判断上传素材是否是音频
                    if (!Director.Util.isValidAudio(params.file_type)) {
                        EpgWeb.Plugin.showTips({content: "上传音频格式只支持mp3, 请重新上传", type: "error"})
                        return;
                    }

                    self.startUploadFile(params, self.AddEffectAudio);

                });
            },

            AddEffectImage: function (data, params) {
                var self = this;
                var element = Director.Config.EFFECT_DEFAULTS['image'];

                var entity = Director.Util.getEntity();

                element.directorId = entity.id;
                element.programQipuId = entity.programQipuId;
                element.url = data.httpInnerUrl;
                element.type = 1;
                element.name = params.file.name;

                element = JSON.stringify(element);

                Director.Dao.addEffect({'data': element}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.refreshEffectList(1);
                    }
                })
            },

            AddEffectAudio: function (data, params) {
                var self = this;
                var element = {};

                var entity = Director.Util.getEntity();

                element.directorId = entity.id;
                element.programQipuId = entity.programQipuId;
                element.url = data.httpInnerUrl;
                element.type = 4;
                element.name = params.file.name;
                element.location = '';
                element.extraInfo = '{"volumn":20}';

                element = JSON.stringify(element);

                Director.Dao.addEffect({'data': element}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Director.Util.refreshEffectList(4);
                    }
                })
            },

            setDirectorMainResource: function (mainResourceId) {
                var entity = this.getEntity();
                if (mainResourceId != null) {
                    Director.Dao.setDirectorMainResource({pid: entity.programQipuId, mainResourceId: mainResourceId}, function (data) {
                        if (data != null && data.code == "A00000") {
                            console.log("设置主信号源：" + data);
                            var elementDom = $("div[data-div-id=" + mainResourceId + "]");
                            if (typeof(elementDom) == "undefined"){
                                $("#imgLogo_mainResource").appendTo(Director.Config.ImgLogoMainResource);
                            } else {
                                $("#imgLogo_mainResource").appendTo(elementDom);
                            }
                            EpgWeb.Plugin.showTips({content: "设置成功"});
                        } else {
                            EpgWeb.Plugin.showTips({content: data.msg, type: "error"});
                        }

                    });
                }
            },

        }
    )
});
